package com.ldzl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldzl.dto.CapacityDTO;
import com.ldzl.dto.FrozenStateDTO;
import com.ldzl.pojo.CkItemRecpt;
import com.ldzl.pojo.CkStorageArea;
import com.ldzl.pojo.CkStorageLocation;
import com.ldzl.pojo.CkWarehouse;
import com.ldzl.service.CkItemRecptService;
import com.ldzl.service.CkStorageAreaService;
import com.ldzl.service.CkStorageLocationService;
import com.ldzl.service.CkWarehouseService;
import com.ldzl.mapper.CkWarehouseMapper;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.BasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 风止
* @description 针对表【ck_warehouse(仓库表)】的数据库操作Service实现
* @createDate 2025-07-10 16:37:29
*/
@Service
@Transactional
public class CkWarehouseServiceImpl extends ServiceImpl<CkWarehouseMapper, CkWarehouse>
    implements CkWarehouseService{
    @Autowired
    private BasicService bs; // 调用主数据服务

    @Autowired
    private CkStorageAreaService sas; // 调用库区服务

    @Autowired
    private CkStorageLocationService sls; // 调用库位服务
    @Autowired
    private CkItemRecptService irs; // 调用采购入库服务

    /**
     * 查询所有仓库信息
     * @return
     */
    @Override
    public List<CkWarehouse> findWarehouse(CkWarehouse  warehouse) {
        //查询所有仓库信息
        List<CkWarehouse> listWar = super.baseMapper.selectWarehouse(warehouse);
        //查询所有仓库的容量信息
        List<CapacityDTO> capList = super.baseMapper.findCapacity_w();
        //计算每个仓库当前已用容量
        for (CkWarehouse war : listWar) {
            for (CapacityDTO cap : capList) {
                if (war.getWarehouse_id().equals(cap.getWarehouse_id())) {
                    // 检查 max_weight 是否为零或 null
                    if (cap.getMax_weight() != null && cap.getMax_weight().compareTo(BigDecimal.ZERO) != 0) {
                        // 计算已用容量百分比
                        BigDecimal percentage = cap.getUsed_weight()
                                .divide(cap.getMax_weight(), 4, BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal("100"));

                        // 设置保留两位小数
                        percentage = percentage.setScale(2, BigDecimal.ROUND_HALF_UP);

                        System.out.println("测试容量百分比：" + percentage + "%");
                        war.setUsed_capacity(percentage);
                    } else {
                        // 如果 max_weight 为零或 null，可以设置默认值或进行其他处理
                        System.out.println("最大容量为零或 null，无法计算百分比。");
                        war.setUsed_capacity(BigDecimal.ZERO); // 设置默认值为0
                    }
                }
            }
        }
        return listWar;
    }

    /**
     * 获取仓库编码
     * @param encode
     * @return
     */
    @Override
    public AjaxResult getNumber(Long encode) {
        return bs.automaticallyNumbers( encode);
    }

    /**
     * 新增/修改 仓库
     * @param warehouse
     * @return
     */
    @Override
    public int saveWarehouse(CkWarehouse warehouse) {

        //判断仓库唯一性
        CkWarehouse war = super.getOne(new QueryWrapper<CkWarehouse>()
                .eq("warehouse_name",warehouse.getWarehouse_name())
                .eq("is_delete",0)
        );
        if(warehouse.getWarehouse_id() == null){
            //新增数据
            //赋值创建时间和更新时间
            warehouse.setCreate_time(new Date());
            warehouse.setUpdate_time(new Date());

            //判断仓库唯一性
            if(war != null)
                return 3; //仓库已存在
        }else{
            //使用id查询
            CkWarehouse war2 = super.getOne(new QueryWrapper<CkWarehouse>()
                    .eq("warehouse_id",warehouse.getWarehouse_id())
                    .eq("is_delete",0)
            );
            if(war != null && !war.getWarehouse_name().equals(war2.getWarehouse_name()))
                return 3; //仓库已存在
            //修改数据
            warehouse.setUpdate_time(new Date());
            //清除创建人
            warehouse.setCreate_by(null);
        }
        if(!super.saveOrUpdate(warehouse))
            return 2; //失败
        return 1; //成功
    }

    /**
     * 修改冻结状态
     * @param fst
     * @return
     */
    @Override
    public boolean updateFrozen(FrozenStateDTO fst) {
        System.out.println("测试修改冻结状态：" + fst);
        if(fst.getType() == 1){
            CkWarehouse warehouse = new CkWarehouse();
            warehouse.setFrozen_flag(fst.getState());
            return super.update(warehouse,new QueryWrapper<CkWarehouse>()
                        .eq("warehouse_id",fst.getId()));
        } else if (fst.getType() == 2) {
            CkStorageLocation location = new CkStorageLocation();
            location.setFrozen_flag(fst.getState());
            return sls.update(location,new QueryWrapper<CkStorageLocation>()
                    .eq("location_id",fst.getId()));
        }else{
            CkStorageArea area = new CkStorageArea();
            area.setFrozen_flag(fst.getState());
            return sas.update(area,new QueryWrapper<CkStorageArea>()
                    .eq("area_id",fst.getId()));
        }
    }

    /**
     * 查询仓库/库区/库位
     * @return
     */
    @Override
    public List<CkWarehouse> selectWarehouse_w_l_a() {
        return super.baseMapper.selectWarehouse_w_l_a();
    }

    /**
     * 删除仓库
     * @param warehouse_id
     * @return
     */
    @Override
    public int deleteWarehouse(Long warehouse_id) {
        //查询引用的采购入库单
        List<CkItemRecpt> list = irs.list(new QueryWrapper<CkItemRecpt>()
                .eq("is_delete", 0)
                .eq("warehouse_id", warehouse_id)
                .notIn("status", 1, 6));
        if(list != null && list.size() > 0)
            return 3; //入库单存在引用 无法删除
        CkWarehouse warehouse = new CkWarehouse();
        warehouse.setWarehouse_id(warehouse_id);
        warehouse.setIs_delete("1");

        //先删除入库单的引用
        irs.delete_warehouse_id(warehouse_id);

        //删除对应的库库区
        List<CkStorageLocation> locations = sls.list(new QueryWrapper<CkStorageLocation>()
                .eq("warehouse_id",warehouse_id)
                .eq("is_delete",0)
        );

        locations.forEach( location -> {
            //删除对应的库位
            if(!sas.delete_location_id(location.getLocation_id()))
                System.out.println("删除库位失败：" + location.getLocation_id());
        });
        if(!sls.delete_warehouse_id(warehouse_id))
            System.out.println("删除库区失败：" + warehouse_id);

        //删除仓库
        if (!super.saveOrUpdate(warehouse))
            return 1;//删除失败
        return 0;
    }

    /**
     * 批量删除仓库
     * @param ids
     * @return
     */
    @Override
    public String deleteWarehouse_batch(List<Long> ids) {
        String isSuccess = "仓库id为：";

        List<CkWarehouse> listWar = new ArrayList<>();
        for (Long warehouse_id : ids) {
            CkWarehouse warehouse = new CkWarehouse();
            warehouse.setWarehouse_id(warehouse_id);
            warehouse.setIs_delete("1");

            //查询引用的采购入库单
            List<CkItemRecpt> list = irs.list(new QueryWrapper<CkItemRecpt>()
                    .eq("is_delete", 0)
                    .eq("warehouse_id", warehouse_id)
                    .notIn("status", 1, 6));
            if(list != null && list.size() > 0)
                isSuccess = isSuccess + warehouse_id +","; //入库单存在引用 无法删除
            else
                listWar.add(warehouse);

        }
        isSuccess = isSuccess + "的入库单存在引用，无法删除";
        if (!super.saveOrUpdateBatch(listWar))
            return "fail";
        return isSuccess;
    }

}




